<script setup>
  import { reactive, ref, onMounted } from 'vue'
  import { verifyPhone, verifyCode } from '@/utils/verify'
  import { getCodeApi } from '@/api/user'
  import {
    showNoneIconToast,
    showSuccessToast,
    showErrorToast
  } from '@/utils/toast'

  import {
    useUserStore,
    useChatStore,
    useSessionStore
  } from '@/stores'
  import { onLoad } from '@dcloudio/uni-app'
  // 导入 pages.json 的配置对象
  import pagesJson from '@/pages.json'
  import socket from '@/utils/websocket'
  import { UniAppEvent } from '@/constants/common'
  // 导入特性开关
  import { ENABLE_PHONE_LOGIN, BRAND_NAME } from '@/config/feature'
  const chatStore = useChatStore()
  const sessionStore = useSessionStore()

  // 状态栏高度
  const statusBarHeight = ref(0)
  
  // 登录成功后，优先要回跳的页面路由路径
  let redirectUrl = null
  
  // onMounted: 获取状态栏高度
  onMounted(() => {
    const info = uni.getSystemInfoSync()
    statusBarHeight.value = info.statusBarHeight || 20
  })
  
  // onLoad: 小程序页面的生命周期之一，在加载页面的时候会自动执行，
  // 参数是上个页面携带的参数
  onLoad((query) => {
    redirectUrl = query.redirectUrl
  })

  // 返回
  const onBack = () => {
    const pages = getCurrentPages()
    if (pages.length >= 2) {
      uni.navigateBack()
    } else {
      uni.switchTab({
        url: '/pages/index/index'
      })
    }
  }

  // 回到首页
  const onGoHome = () => {
    // 触发(通知)全局自定义事件 GoToHomePage
    uni.$emit(UniAppEvent.GoToHomePage)
    uni.switchTab({
      url: '/pages/index/index'
    })
  }

  // 新增：导航按钮功能
  const goHome = () => uni.switchTab({ url: '/pages/index/index' })
  const goMine = () => uni.switchTab({ url: '/pages/mine/mine' })

  // 验证码
  let codeValue = null
  // 登录表单
  const loginForm = reactive({
    phone: '', // 手机号
    code: '' // 验证码
  })

  // 剩余时间
  const timeLeft = ref(0)

  // 获取验证码+倒计时
  const getCode = async () => {
    const { phone } = loginForm
    // 获取手机号并校验
    if (!verifyPhone(phone)) return

    // 如果在倒计时中，则无需再请求了
    if (timeLeft.value > 0) {
      showNoneIconToast('请在60秒后重新获取')
      return
    }
    try {
      // 发请求（请求验证码）
      codeValue = await getCodeApi(phone)
      // 倒计时（更新界面）
      timeLeft.value = 60
      // 开启间歇定时器
      const timer = setInterval(() => {
        // 每隔1秒，剩余时间自减 1
        timeLeft.value--
        if (timeLeft.value === 0) {
          // 关闭定时器
          clearInterval(timer)
          timeLeft.value = 0
        }
      }, 1000)
    } catch (e) {
      timeLeft.value = 0
      showNoneIconToast(e.message)
    }
  }

  // 是否勾选协议
  const isAgree = ref(false)
  // 控制登录按钮的加载状态
  const codeLoading = ref(false)
  const wxLoading = ref(false)

  // 勾选切换
  const onToggle = () => {
    isAgree.value = !isAgree.value
  }
  const userStore = useUserStore()

  // 公共登录函数：
  // 把两种登录方式都需要执行的代码统一放到这个函数中进行编写
  // 把不同的代码进行参数的传递
  const onLogin = (loginFn) => {
    // 判断小图标是否勾选
    if (!isAgree.value) {
      showNoneIconToast('请勾选并同意用户协议')
      return
    }
    // loginFn: 代指一个函数，今后传入的是手机号+验证码的登录代码或微信一键登录的代码
    // 并且 loginFn 函数返回值必须是一个 Promise 实例，这样的话，调用 loginFn 函数的时候
    // 可以知道当前登录是成功还是失败
    // 调用具体的登录函数前，把按钮设置为加载中，给用户 loading 提示
    // 登录成功后统一做页面跳转操作
    loginFn()
      // 成功
      .then(async () => {
        try {
          // 登录成功的提示
          showSuccessToast('登录成功')
          // 主动建立 websocket 连接
          socket.initSocketConnect()
          // 获取会话列表
          await sessionStore.getSessionListAction()
          // 通知(对方)登录成功
          uni.$emit(UniAppEvent.LoginSuccess)
        } catch (e) {
          console.log(e)
        }
        // 获取用户信息
        userStore
          .getUserInfoAction()
          .then(() => {})
          .catch((e) => {
            showNoneIconToast(e.message)
          })
        // 页面跳转: 目前统一跳转至首页（今后会有很多跳转细节，ToDo)
        setTimeout(() => {
          // 说明携带了要回跳路由路径，此时需要跳转至 redirectUrl 的路径
          if (redirectUrl) {
            // 判断 redirectUrl 是不是 tabbar 路径
            const isTabBarPage = pagesJson.tabBar.list.some(
              (route) => route.pagePath === redirectUrl
            )
            // 如果是：uni.switchTab
            if (isTabBarPage) {
              uni.switchTab({
                url: '/' + redirectUrl
              })
            } else {
              // 否则：uni.redirectTo
              // redirectTo 与 navigateTo 的区别：
              // 相同点：都可以做页面跳转
              // 不同点：navigateTo 不会关闭当前页面，回退的时候会返回到当前当前页
              //        redirectTo 会关闭当期那页面，回退的时候不会返回到当前页
              if (
                // 本人并且携带的路由路径还是聊天页，由于本人不能自己聊天，压根就去不了聊天
                chatStore.fangDong.id === userStore.userInfo.userId &&
                redirectUrl === 'pages/chat/chat'
              ) {
                showNoneIconToast('不能与自己聊天')
                uni.redirectTo({
                  url:
                    '/pages/detail/detail?houseId=' +
                    chatStore.house.houseId
                })
              } else {
                uni.redirectTo({
                  url: '/' + redirectUrl
                })
              }
            }
          } else {
            uni.switchTab({
              url: '/pages/index/index'
            })
          }
        }, 500)
      })
      // 失败
      .catch((error) => {
        showErrorToast(error.message)
      })
  }

  // 验证码登录
  const onLoginByCode = () => {
    onLogin(() => {
      return new Promise((resolve, reject) => {
        const { phone, code } = loginForm
        // 做校验：当校验不通过，需要手动调用 reject 函数，将Promise设置为失败的
        if (!verifyPhone(phone)) return reject()
        if (!verifyCode(code)) return reject()
        if (code !== codeValue) {
          showNoneIconToast('验证码不正确')
          return reject()
        }
        codeLoading.value = true
        // 调用 loginByCodeAction 函数
        userStore
          .loginByCodeAction(loginForm)
          // 更新Promise实例状态为成功
          .then(resolve)
          // 更新Promise实例状态为失败
          .catch(reject)
          .finally(() => {
            codeLoading.value = false
          })
      })
    })
  }

  // 微信一键登录
  const onLoginByWx = () => {
    onLogin(() => {
      return new Promise((resolve, reject) => {
        wxLoading.value = true
        // 获取微信登录凭证 code
        uni.login({
          provider: 'weixin',
          success: (res) => {
            // 成功了，通过 res.code 获取微信登录凭证

            uni.request({
              method: 'GET',
              url: 'https://api.weixin.qq.com/sns/jscode2session',
              data: {
                appid: 'AppID(小程序ID)',
                secret: '你的AppSecret(小程序密钥)',
                js_code: res.code,
                grant_type: 'authorization_code'
              },
              success: (result) => {
                // 基于 openid 实现微信登录
                userStore
                  .loginByWxAction(result.data.openid)
                  .then(resolve)
                  .catch(reject)
                  .finally(() => {
                    wxLoading.value = false
                  })
              },
              // 失败
              fail: (error) => {
                reject(new Error(error.errMsg))
                wxLoading.value = false
              },
              complete: () => {
                uni.hideLoading({
                  fail: () => {}
                })
              }
            })
          },
          fail: (error) => {
            reject(new Error(error.errMsg))
            wxLoading.value = false
          }
        })
      })
    })
  }
</script>

<template>
  <view class="login-page">
    <!-- 顶部：左双按钮 + 居中标题 + 右等宽占位 -->
    <view class="nav" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-inner">
        <view class="icon-pair">
          <view class="icon-btn" @tap="goHome" aria-label="去首页">🏠</view>
          <view class="icon-btn" @tap="goMine" aria-label="去我的">‹</view>
        </view>
        <text class="nav-title">{{ BRAND_NAME }}</text>
        <view style="width:140rpx"></view>
      </view>
    </view>

    <!-- 中部视觉：品牌卡片 + 标语 -->
    <view class="brand-card">
      <image class="brand-lockup" src="https://study-test-huangyi.oss-cn-beijing.aliyuncs.com/study-test/web/profile/logo.png?x-oss-credential=LTAI5t7pBt49prZPvkWgKP2W%2F20250929%2Fcn-beijing%2Foss%2Faliyun_v4_request&x-oss-date=20250929T002713Z&x-oss-expires=3600&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-signature=aa5ea3e7a066ad95121b1b509bbb8f82787320a515c98adfe6ee27c9c9a4e8ca" mode="widthFix" />
    </view>
    <text class="brand-slogan">让租房更安心</text>

    <!-- 主按钮 -->
    <button class="btn-primary" @tap="onLoginByWx" :loading="wxLoading" :disabled="wxLoading">
      微信一键登录
    </button>

    <!-- 手机号验证码：保留代码，默认不渲染 -->
    <view v-if="ENABLE_PHONE_LOGIN" class="phone-login-wrap">
      <!-- 标题 -->
      <view class="title">
        <view class="level1">手机号快捷登录</view>
        <view class="level2">未注册过的手机号将自动创建账号</view>
      </view>
      
      <!-- 表单 -->
      <view class="form">
        <view class="form-item">
          <input
            type="text"
            placeholder="手机号"
            class="form-item__input"
            v-model.trim="loginForm.phone"
          />
        </view>
        <view class="form-item">
          <input
            type="text"
            placeholder="验证码"
            class="form-item__input code"
            v-model.trim="loginForm.code"
          />
          <text class="btn-code" @click="getCode">
            {{
              timeLeft > 0 ? `${timeLeft}秒后重新获取` : '获取验证码'
            }}
          </text>
        </view>
        <view class="form-item">
          <button
            class="btn btn-phone-login"
            plain
            :loading="codeLoading"
            :disabled="codeLoading"
            @click="onLoginByCode"
          >
            立即登录
          </button>
        </view>
      </view>
    </view>

    <!-- 协议区 -->
    <view class="agreement-wrap">
      <bit-icon
        :name="isAgree ? 'agree' : 'unagree'"
        size="22"
        @click="onToggle"
        class="icon"
      />
      <view class="text" @click="onToggle">
        <text class="text_default">
          我已阅读并同意
        </text>
        <text class="text_active">《用户协议》</text>
        <text class="text_default">和</text>
        <text class="text_active">《隐私政策》</text>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
  @import '@/styles/variables.scss';
  
  // 品牌颜色常量
  $brand-primary: #07C160;
  $brand-text: #2E3A44;
  $brand-subtext: #5B6670;

  .login-page {
    min-height: 100vh;
    /* 柔和浅绿渐变：彻底替代任何 shadow-grey.png */
    background: linear-gradient(180deg, rgba(7,193,96,.06) 0%, rgba(7,193,96,.02) 100%);
    display: flex;
    flex-direction: column;
    padding-bottom: 48rpx;
  }

  .nav {
    position: sticky;
    top: 0;
    background: #fff;
    z-index: 100;
  }

  .nav-inner {
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24rpx;
  }

  .nav-title {
    font-size: 32rpx;
    font-weight: 600;
    color: $brand-text;
  }

  .icon-pair {
    display: flex;
    align-items: center;
    gap: 12rpx;
  }

  .icon-btn {
    width: 64rpx;
    height: 64rpx;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #F4F6F8;
    color: $brand-text;
    font-size: 28rpx;
    transition: all 0.2s ease;

    &:active {
      opacity: 0.85;
      transform: scale(0.95);
    }
  }

  /* 新的中部品牌卡片 */
  .brand-card {
    width: 560rpx;
    padding: 32rpx 28rpx;
    margin: 24rpx auto 0;
    background: #fff;
    border-radius: 24rpx;
    box-shadow: 0 16rpx 40rpx rgba(7,193,96,.08);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .brand-lockup {
    width: 480rpx;
    height: auto;
  }

  .brand-slogan {
    margin-top: 24rpx;
    text-align: center;
    color: $brand-text;
    opacity: 0.8;
    font-size: 28rpx;
  }

  .btn-primary {
    width: 86%;
    height: 96rpx;
    line-height: 96rpx;
    margin: 48rpx auto 0;
    text-align: center;
    border-radius: 48rpx;
    background: $brand-primary;
    color: #fff;
    font-size: 34rpx;
    font-weight: 700;
    box-shadow: 0 12rpx 24rpx rgba(7,193,96,.18);
    border: none;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
      box-shadow: 0 6rpx 12rpx rgba(7,193,96,.25);
    }

    &[disabled] {
      opacity: 0.6;
      transform: none;
    }
  }

  // 手机号登录区域（当特性开关开启时显示）
  .phone-login-wrap {
    width: 100%;
    padding: 40rpx;

    .title {
      text-align: center;
      margin-bottom: 60rpx;

      .level1 {
        font-size: 42rpx;
        font-weight: 600;
        color: $brand-text;
        margin-bottom: 12rpx;
      }
      .level2 {
        font-size: 24rpx;
        color: $brand-subtext;
      }
    }

    .form {
      &-item {
        position: relative;
        margin-bottom: 30rpx;

        &__input {
          box-sizing: border-box;
          width: 100%;
          height: 110rpx;
          padding-left: 30rpx;
          border-radius: 24rpx;
          background: #fff;
          border: 2rpx solid #f0f0f0;
          transition: border-color 0.3s;

          &:focus {
            border-color: $brand-primary;
          }

          &.code {
            padding-right: 200rpx;
          }
        }

        .btn-code {
          position: absolute;
          right: 30rpx;
          top: 50%;
          transform: translateY(-50%);
          font-size: 28rpx;
          color: $brand-primary;
          padding: 10rpx 20rpx;
          background: #f8f8f8;
          border-radius: 16rpx;
        }

        .btn {
          width: 100%;
          height: 110rpx;
          line-height: 110rpx;
          border-radius: 24rpx;
          border: none;
          font-size: 32rpx;
          font-weight: 600;

          &.btn-phone-login {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #fff;
            box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.3);
          }
        }
      }
    }
  }

  .agreement-wrap {
    margin-top: auto;
    padding: 48rpx 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .icon {
      margin-right: 12rpx;
      flex-shrink: 0;
    }

    .text {
      font-size: 24rpx;
      line-height: 1.5;

      .text_default {
        color: #666;
      }

      .text_active {
        color: $brand-primary;
        text-decoration: underline;
      }
    }
  }
</style>
